var express = require('express');
var router = express.Router();
var Article = require('../db/article');
/* GET home page. */
var getTop=function (pageSize,callback) {
  var query = Article.find({});
  query.limit(pageSize);
  query.exec(function (err, docs) {
    callback(err,docs);
  });
};
function index(req, res) {
  var page = req.query.page;
  if (!page) {
    page = 1;
  }
  var pageSize = 10;
  console.log("page:" + page + ",rows:" + pageSize);
  var query = Article.find({});
  query.skip((page - 1) * pageSize);
  query.limit(pageSize);
  //计算分页数据
  var obj="";
  query.exec(function (err, docs) {
    if (err) {
      res.send(err);
    } else {
      //计算数据总数
      Article.find().count(function (err, count) {
        if (err) return;
        var  totalPages =Math.ceil(count / pageSize);
        res.render('blog', {
          title:"照片",
          articles: docs,
          total: count,
          page: page,
          totalPages: totalPages
        });
      });
    }
  });
}

router.get('/', function(req, res, next) {
  getTop(10,function(err,obj){
    res.render('index', {articles:obj});
  });
});
router.get('/mySite', function(req, res, next) {
  res.render('mySite');
});
router.get('/full', function (req, res) {
  var article={
    _id:req.query.article
  };
  Article.findOne(article, function (err, doc) {
    if (err) {
      return;
    }
    if (doc == "") {

    } else {
      console.log(doc);
      res.render('full_text', { article: doc });
    }
  });
});
router.get('/blog', function (req, res) {
  index(req,res);
});
module.exports = router;
